#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class Computer
{
public:
    Computer(const char * brand,double price)
    : _brand(new char[strlen(brand) + 1]())
    , _price(price)
    {
        strcpy(_brand,brand);
        cout << "Computer(const char *,double)" << endl;
    }

    void print(){
        cout << "brand:" << _brand << endl;
        cout << "price:" << _price << endl;
    }

    ~Computer(){
        cout << "~Computer()" << endl;
        if(_brand){
            delete [] _brand;
            _brand = nullptr;
        }
    }

    //默认拷贝构造函数不够用了
    /* Computer(const Computer & rhs) */
    /* : _brand(rhs._brand)//char * _brand = rhs._brand; */
    /* , _price(rhs._price)//double _price = rhs._price; */
    /* { */
    /*     cout << "拷贝构造" << endl; */
    /* } */

    Computer(const Computer & rhs)
    : _brand(new char[strlen(rhs._brand) + 1]())
    , _price(rhs._price)
    {
        strcpy(_brand,rhs._brand);
        cout << "拷贝构造" << endl;
    }

    //默认的赋值运算符函数不够用了
    /* Computer & operator=(const Computer & rhs){ */
    /*     cout << "赋值运算符函数" << endl; */
    /*     _brand = rhs._brand;//浅拷贝 */
    /*     _price = rhs._price; */
    /*     return *this; */
    /* } */

    Computer & operator=(const Computer & rhs){
        cout << "赋值运算符函数" << endl;
        if(this != &rhs){//1.考虑自赋值情况
            delete [] _brand;//2.回收原本管理的堆空间
            _brand = new char[strlen(rhs._brand) + 1]();
            strcpy(_brand,rhs._brand);//3.深拷贝
            _price = rhs._price;//以及其他的数据成员的赋值
        }
        return *this;//4.返回本对象
    }
private:
    char * _brand;
    double _price;
};

void test0(){
    Computer pc("Apple",20000);
    /* Computer pc2 = pc; */
    Computer pc2(pc);
    pc2.print();
}

void test1(){
    Computer pc("Apple",20000);
    Computer pc2("Xiaomi",8000);
    pc2 = pc;
    /* pc2 = pc = pc; */
    /* &(pc2 = pc); */
    /* pc = Computer("Asus",7000); */

    //赋值语句的本质
    /* pc2.operator=(pc); */
    pc2.print();

    //自赋值语句
    pc = pc;
    pc.print();

    int a = 1,b = 2,c = 3;
    a = b = c;
}

int main(void){
    test1();
    return 0;
}
